<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\RegData;
use Illuminate\Support\Facades\DB;
use App\LogData;
use App\Res;

class IndexController extends Controller
{
    //
    public function update_reg(RegData $regData){
        set_time_limit(0);

        $sql = $regData->select(['*']);
           // ->count();

        $count_success = [];  // 成功的记录

        foreach ($sql->cursor() as $record) {
           //var_dump($record);die;
            try {
                $data = [
                    'reg_time2' => date("Y-m-d H:i:s", $record->reg_time),
                    'ip2' => long2ip($record->ip),
                ];
                $res = $regData->where('id',$record->id)->update($data);
                var_dump($res);die;
            } catch (\Exception $e) {
                // todo
                var_dump(22);die;
            }
        }
    }

    public function insert_log(){
        set_time_limit(0);
        date_default_timezone_set('Asia/Shanghai');
        $all_date = $this->periodDate('2021-09-27','2021-10-05');
        $total = 0;
        foreach ($all_date as $time_date){
            for ($i=1; $i<=3; $i++)
            {
                if($total >= 500){
                    $total = 0;
                    sleep(1);
                }
                $file ="./msdk.zantainet.com_php_only_".$time_date.'_'.$i.'.log';
                $fhandle = fopen($file, "r");
                if($fhandle !== FALSE) {
                    while (($line = fgets($fhandle)) !== false) {
                        //echo $line;die;
                        // $ip = substr($line, 0, strpos($line, '- -')-1);//提取ip
                        $time = $this->get_between($line,'[',']');
                        if($time){

                            $times =  explode('+',$time);
                            //var_dump($times);die;
                            $time3 =  explode('/',$times[0]);
                            $time4 =  explode(':',$time3[2]);
                            if($time3[1] == 'Sep'){
                                $date = $time4[0].'-'.'09-'.$time3[0].' '.$time4[1].':'.$time4[2].':'.$time4[3];
                            }elseif($time3[1] == 'Oct'){
                                $date = $time4[0].'-'.'10-'.$time3[0].' '.$time4[1].':'.$time4[2].':'.$time4[3];
                            }
                            //var_dump(strtotime($date));die;
                        }
                        $from = $this->get_between($line,'?c=','&');
                        $game_data =  explode('_',$from);
                        if($game_data){
                            $game_id = $game_data[0];
                            $agent_id = $game_data[1];
                            $site_id = $game_data[2];
                        }
                        //ip=
                        $ip = $this->get_between($line,'ip=','&amp;callback_url');
                        $idfa = $this->get_between($line,'idfa=','&amp;ts');

                        //var_dump($ip);die;
                        if(!empty($game_id) && !empty($agent_id) && !empty($site_id)){
                            DB::table('log_data')->insert([
                                'ip'=>$ip,
                                'idfa'=>$idfa,
                                'game_id'=>$game_id,
                                'agent_id'=>$agent_id,
                                'site_id'=>$site_id,
                                'reg_time'=>$date,
                                'reg_time2'=>strtotime($date),
                                'reg_time3'=>date("Y-m-d",strtotime($date)),
                                'log'=>$line,
                            ]);
                            $total ++;
                        }

                    }fclose($fhandle);
            }

            }
        }

    }


    function get_between($input, $start, $end) {
        $substr = substr($input, strlen($start)+strpos($input, $start),(strlen($input) - strpos($input, $end))*(-1));
        if(!$substr){
            $substr = '';
        }
        return $substr;
    }

    public function pp(RegData $regData,LogData $logData){
//（（注册数据时间-1天）< 日志时间）&&（注册数据时间> 日志时间）&& (（注册设备imei = 日志设备idfa）||（注册设备ip = 日志设备ip）)&&（游戏id相同）
        set_time_limit(0);
        date_default_timezone_set('Asia/Shanghai');
        $data = $regData->select(['*'])->get()->toArray();
        $data2 = $logData->get()->toArray();
        $total =0;
        foreach ($data as $k=>$v){

            $time2 = $v['reg_time'] - 86400;
            //$total =0;
            foreach ($data2 as $kk=>$vv){

                $total++;
                if($time2 < $vv['reg_time2'] && $v['reg_time']>$vv['reg_time2']){
                    if($v['ip'] == $vv['ip'] || $v['imei']==$vv['idfa']){
                        if($v['game_id'] == $vv['game_id']){
                                $new[] = [
                                    'id'=>$v['id'],
                                    'log_data'=>$vv['log'],
                                    'user_name'=>$v['user_name'],
                                    'agent_id'=>$vv['agent_id'],
                                    'site_id'=>$vv['site_id'],
                                    'reg_time'=>$vv['reg_time2'],
                                    'reg_time2'=>$vv['reg_time'],
                                    'game_id'=>$vv['game_id'],
                                ];
                                DB::table('res')->insert($new);
                        }
                    }
                }
               // $total++;
            }
        }
        var_dump($new,$total);die;


    }

    public function qc(RegData $regData,LogData $logData,Res $res){
        set_time_limit(0);
        date_default_timezone_set('Asia/Shanghai');

        $sql = '';
        $sql2 = '';
        $arr = DB::select("select * from
        (select * from res
order by reg_time ASC limit 100000)
as a group by a.user_name,a.game_id");
        //var_dump($arr);die;
        foreach ($arr as $v){
            DB::table('reg_data')->where('user_name',$v->user_name)->update([
                'log_data'=>$v->log_data,
            ]);
            $sql .= "UPDATE db_www.user_imei SET agent_id={$v->agent_id},site_id={$v->site_id} WHERE user_name='{$v->user_name}';".PHP_EOL;

            $sql2 .= "UPDATE db_pay.pay_list SET agent_id={$v->agent_id},placeid={$v->agent_id} WHERE user_name='{$v->user_name}';".PHP_EOL;
        }

        var_dump($sql,$sql2);

    }

    function periodDate($startDate, $endDate)
    {
        $startTime = strtotime($startDate);
        $endTime = strtotime($endDate);
        $arr = [];
        while ($startTime <= $endTime)
        {
            $arr[] = date('Y-m-d', $startTime);
            $startTime = strtotime('+1 day', $startTime);
        }
        return $arr;
    }

    // Returns the next higher or lower number
    function NextRelatedNumber($number, $range){
        $r = $number % $range;
        $f = $number - $r;
        $b = round($r / $range, 0);
        return ($b == 1) ? $f + $range : $f;
    }

}
